<!--  新增库存盘点 -->
<template>
  <el-drawer
    show-close
    :before-close="handleClose"
    title="新增调拨单"
    :visible="addDialogVisible"
    size="60%"
  >
    <div style="height: 80vh; overflow: auto">
      <el-form
        ref="form"
        :model="queryParams"
        label-width="110px"
        size="small"
        style="margin: 0px 20px"
      >
        <el-row>
          <el-col :span="18">
            <el-form-item label="盘点仓库/门店" prop="stationId">
              <el-select
                style="width: 40%"
                v-model="queryParams.stationId"
                placeholder="请选择盘点仓库/门店"
                @change="changeStationList"
              >
                <el-option
                  v-for="item in stationList"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6"> 操作人： {{ $store.state.user.name }} </el-col>
        </el-row>
      </el-form>
      <div style="margin: 0px 20px">
        <div class="drawer-div">
          <span>选择商品</span>
        </div>
        <div class="drawer-data">
          <div>
            <div class="drawer-tree-input">
              <el-tree
                class="drawer-tree"
                :data="dataTree"
                :props="defaultProps"
                node-key="categoryId"
                @node-click="handleNodeClick"
                :default-expanded-keys="dataTreeId"
                v-loading="loadingTree"
              ></el-tree>
            </div>
            <div style="text-align: center">
              <el-input
                placeholder="输入条码后按回车"
                v-model="commodityCode"
                size="small"
                clearable
                style="width: 170px"
                @keyup.enter.native="inputCarriageReturn()"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
          </div>
          <div></div>
          <el-table :data="gridData" border height="400">
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column
              property="commodityName"
              label="商品名称"
              width="100"
            ></el-table-column>
            <el-table-column
              property="barCode"
              label="商品条码"
            ></el-table-column>
            <el-table-column
              property="categoryName"
              label="商品分类"
              width="100"
            ></el-table-column>
            <el-table-column
              property="unit"
              label="单位"
              width="100"
            ></el-table-column>
            <el-table-column
              property="inventoryNum"
              label="盘点数量"
              width="180"
            >
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  :precision="0"
                  v-model="scope.row.inventoryNum"
                  :min="0"
                  :max="100000"
                  label="请输入"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              property="inventory"
              label="系统数量"
              width="100"
            ></el-table-column>
            <el-table-column
              property="differenceNum"
              label="差异数量"
              width="100"
              :formatter="formatterTotalPrice"
            ></el-table-column>
            <el-table-column
              property="status"
              label="状态"
              width="100"
              :formatter="formatterStatus"
            >
            </el-table-column>
            <el-table-column property="notes" label="备注" width="180">
              <template slot-scope="scope">
                <el-input
                  size="mini"
                  type="text"
                  placeholder="请输入备注"
                  v-model="scope.row.notes"
                  maxlength="50"
                  show-word-limit
                >
                </el-input
              ></template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="60">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="deleteProduct(scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="div-span">
          <span>总计： </span>
          <span></span>
          <span></span>
          <span>{{ inventoryNum }} </span>
          <span>{{ originalNum }}</span>
          <span>{{ differenceNum }}</span>
          <span></span>
        </div>
        <div class="div-button">
          <div>
            <el-button
              type="primary"
              size="small"
              @click="save"
              :disabled="saveDisabled"
              >保存</el-button
            >
            <el-button size="small" @click="cancelPutStorage">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import { cloneDeep } from "lodash";
import {
  queryByBarCode,
  getNonOilCategoryTreeAndCommodity,
  getRepository,
} from "@/api/nonOil/putlntoStorage";
import { batchSave } from "@/api/nonOil/goods";

export default {
  name: "AddStockCount",
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 出库入库门店列表
      stationList: [],

      // 编码
      commodityCode: null,

      loadingTree: false,
      saveDisabled: false,
      queryParams: {
        stationId: null,
        inventoryDetailsList: [],
      },
      gridData: [],
      dataTree: [],
      dataTreeId: [],
      defaultProps: {
        children: "children",
        label: "categoryName",
      },
    };
  },
  created() {},
  methods: {
    // 格式差异数量
    formatterTotalPrice(row, column) {
      let differenceNum;
      differenceNum = parseFloat(
        (row.inventoryNum - row.inventory).toFixed(10)
      );
      row.differenceNum = differenceNum;
      return differenceNum;
    },

    // 格式状态
    formatterStatus(row, column) {
      let status;

      if (row.differenceNum == 0) {
        row.status = 0;
        status = "账实相符";
      }
      if (row.differenceNum > 0) {
        row.status = 1;
        status = "盘盈";
      }
      if (row.differenceNum < 0) {
        row.status = 2;
        status = "盘亏";
      }

      return status;
    },

    // 查询油站
    getStationList() {
      const enterpriseId = this.presentEnterprise?.enterpriseId
        ? this.presentEnterprise.enterpriseId
        : null;
      getRepository({ enterpriseId, status: "1" }).then((res) => {
        this.stationList = res;
        this.queryParams.stationId = this.stationList[0].stationId;
        this.getNonOilCategoryTree();
      });
    },

    // 选择了油站
    changeStationList() {
      this.getNonOilCategoryTree();
      this.gridData = [];
    },

    // 点击保存
    save() {
      this.saveDisabled = true;
      this.gridData.forEach((item) => {
        item.originalNum = item.inventory;
        item.totalPrice = item.inventoryQuantity * item.salePrice;
      });

      batchSave({
        ...this.queryParams,
        inventoryDetailsList: this.gridData,
      })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess(res.msg);
            this.$emit("update:addDialogVisible", false);
          } else {
            this.msgError(es.msg);
          }
          this.saveDisabled = false;
        })
        .catch(() => {
          this.saveDisabled = false;
        });
    },

    // 点击删除
    deleteProduct(index) {
      this.gridData.splice(index, 1);
    },

    // 搜索条形码按回车
    inputCarriageReturn() {
      if (this.commodityCode) {
        this.commodityCode = this.commodityCode.trim();
        queryByBarCode({
          barCode: this.commodityCode,
          stationId: this.queryParams.stationId,
        }).then((res) => {
          if (res.data) {
            if (!res.data.inventoryNum) {
              res.data.inventoryNum = 0;
            }
            if (!res.data.originalNum) {
              res.data.originalNum = 0;
            }

            res.data.differenceNum = 0;

            if (this.gridData.length) {
              let add = 0;
              this.gridData.forEach((item) => {
                if (item.commodityId == res.data.commodityId) {
                  add++;
                }
              });
              if (!add) {
                this.commodityCode = null;
                this.gridData.unshift(res.data);
              } else {
                this.$message("商品已添加，请添加其他商品！");
              }
            } else {
              this.gridData.unshift(res.data);
            }
          } else {
            this.$message("未查询到该商品条码");
          }
        });
      }
    },

    // 获取树形控件数据
    getNonOilCategoryTree() {
      this.loadingTree = true;
      this.dataTree = [];
      this.dataTreeId = [];
      getNonOilCategoryTreeAndCommodity({
        stationId: this.queryParams.stationId,
      })
        .then((res) => {
          this.loadingTree = false;
          this.dataTree.push(res.data);
          this.unfoldTree(this.dataTree);
        })
        .catch(() => {
          this.loadingTree = false;
        });
    },

    // 数据展开
    unfoldTree(dataTree) {
      dataTree.forEach((item) => {
        this.dataTreeId.push(item.categoryId);
        if (item.children) {
          item.children.forEach((itema) => {
            this.dataTreeId.push(itema.categoryId);
            if (itema.children) {
              itema.children.forEach((itemb) => {
                this.dataTreeId.push(itemb.categoryId);
                if (itemb.children) {
                  itemb.children.forEach((itemc) => {
                    this.dataTreeId.push(itemc.categoryId);
                  });
                }
              });
            }
          });
        }
      });
    },

    // 点击取消入库
    cancelPutStorage() {
      this.$emit("update:addDialogVisible", false);
    },

    // 关闭入库
    handleClose(done) {
      this.$emit("update:addDialogVisible", false);
      done();
    },

    // 点击树形控件内容
    handleNodeClick(data) {
      const result = cloneDeep(data);
      if (result.commodity) {
        if (!result.commodity.inventoryNum) {
          result.commodity.inventoryNum = 0;
        }
        if (!result.commodity.originalNum) {
          result.commodity.originalNum = 0;
        }

        result.commodity.differenceNum = 0;

        if (this.gridData.length) {
          let add = 0;
          this.gridData.forEach((item) => {
            if (item.commodityId == result.commodity.commodityId) {
              add++;
            }
          });
          if (!add) {
            this.gridData.unshift(result.commodity);
          } else {
            this.$message("商品已添加，请添加其他商品！");
          }
        } else {
          this.gridData.unshift(result.commodity);
        }
      }
    },
  },
  computed: {
    inventoryNum() {
      let wadake = 0;
      if (this.gridData.length) {
        this.gridData.forEach((item) => {
          wadake = wadake + item.inventoryNum;
        });
      }
      return wadake;
    },
    originalNum() {
      let wadake = 0;
      if (this.gridData.length) {
        this.gridData.forEach((item) => {
          wadake = wadake + item.inventory;
        });
      }
      return wadake;
    },
    differenceNum() {
      let wadake = 0;
      if (this.gridData.length) {
        this.gridData.forEach((item) => {
          wadake = wadake + item.differenceNum;
        });
      }
      return wadake;
    },
  },
  watch: {
    addDialogVisible: {
      deep: true, // 深度监听
      handler(newVal, oldVal) {
        if (newVal) {
          this.getStationList();
        } else {
          this.gridData = [];
          this.commodityCode = null;
          this.$refs.form.resetFields();
        }
      },
    },
  },
};
</script>
<style scoped lang="scss">
.drawer-div {
  height: 40px;
  line-height: 40px;
  padding-left: 10px;
  background-color: #f1f1f1;
  display: flex;
  margin-bottom: 30px;

  span {
    width: 90px;
  }
}

.div-button {
  display: flex;
  justify-content: space-evenly;
  margin-top: 30px;
}

.div-span {
  height: 40px;
  line-height: 40px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: space-evenly;
  margin-top: 30px;
}

.drawer-tree {
  width: 100%;
}

.drawer-data {
  display: flex;
}

.drawer-tree-input {
  width: 100%;
  height: 368px;
  overflow-y: scroll;
}
</style>
